﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Forex.IB.RealTimeBars.Components
{
    public class CSVFileBuilder
    {
        private StringBuilder _stringBuilder = null;

        public CSVFileBuilder()
        {
            _stringBuilder = new StringBuilder();
        }

        public override string ToString()
        {
            return _stringBuilder.ToString();
        }

        public void StartNewRecord()
        {
            _stringBuilder.Append(Environment.NewLine);
        }

        public void Append(string field)
        {
            bool requiresQuotes = false;

            if (field.Contains(' ') || field.Contains(',') || field.Contains(Environment.NewLine))
            {
                requiresQuotes = true;
            }

            if (field.Contains('"'))
            {
                field = field.Replace("\"", "\"\"");
            }

            if (requiresQuotes) field = "\"" + field + "\"";

            if (_stringBuilder.Length > 0 && !_stringBuilder.ToString().EndsWith(Environment.NewLine))
                _stringBuilder.Append(",");

            _stringBuilder.Append(field);
        }



        public static string ConvertToCsv(DataTable dt, bool includeHeaders)
        {
            CSVFileBuilder builder = new CSVFileBuilder();

            if (includeHeaders)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    DataColumn column = dt.Columns[i];
                    builder.Append(column.ColumnName);
                }
                builder.StartNewRecord();
            }


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                if (i > 0) builder.StartNewRecord();

                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    DataColumn column = dt.Columns[j];
                    if (column.DataType.ToString() == "DateTime") column.DefaultValue = string.Empty;

                    builder.Append(row[column.ColumnName].ToString());
                }
            }
            return builder.ToString();
        }
       
    }
}
